package com.huayi.server.NioServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.util.internal.logging.InternalLoggerFactory;
import io.netty.util.internal.logging.Log4J2LoggerFactory;
import io.netty.util.internal.logging.Slf4JLoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class DeviceServer {

    Logger logger = LoggerFactory.getLogger(DeviceServer.class);

    int port = 9000;

    @Autowired
    ServerIntializer serverIntializer;

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workGroup;
    Thread thread;

    @PostConstruct
    public void init() throws InterruptedException {
        logger.debug("server init ...");
        thread = new Thread(runnable);
        thread.start();
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            logger.info("server start ...");
            bossGroup = new NioEventLoopGroup();
            workGroup = new NioEventLoopGroup();

            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(serverIntializer)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childOption(ChannelOption.SO_KEEPALIVE,true);

            ChannelFuture future = null;

            try {
                future = bootstrap.bind(port).sync();
                future.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    @PreDestroy
    public void destory(){
        logger.info("server destory ...");
        bossGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
